<?php

namespace Utuo;

/**
 * 62进制类
 * 
 * @author esinger
 */
abstract class Base62 {
	// 类参数
	private static $configs = array (
			// 'dict' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
			'dict' => 'ugbDkC7is1tpGYPB0eASmhQdzH95xrZLJ8RyflUWMvTKwo3j6O24IncFNqVEaX',
			'base' => 62,
			'offset' => 24776336 
	);
	
	/**
	 * 设置配置参数
	 *
	 * @param string|array $name
	 * @param string $value
	 */
	public static function setConfig($name, $value = null) {
		if (is_array ( $name )) {
			self::$configs = array_merge ( self::$configs, $name );
		} else {
			self::$configs [$name] = $value;
		}
	}
	
	/**
	 * 10进制转为62进制
	 *
	 * @param integer $n 10进制数值
	 * @return string 62进制
	 */
	public static function encode($n) {
		$n += self::$configs ['offset'];
		$ret = '';
		for($t = floor ( log10 ( $n ) / log10 ( self::$configs ['base'] ) ); $t >= 0; $t --) {
			$a = floor ( $n / pow ( self::$configs ['base'], $t ) );
			$ret .= substr ( self::$configs ['dict'], $a, 1 );
			$n -= $a * pow ( self::$configs ['base'], $t );
		}
		return $ret;
	}
	
	/**
	 * 62进制转为10进制
	 *
	 * @param integer $n 62进制
	 * @return string 10进制
	 */
	public static function decode($s) {
		$ret = 0;
		$len = strlen ( $s ) - 1;
		for($t = 0; $t <= $len; $t ++) {
			$ret += strpos ( self::$configs ['dict'], substr ( $s, $t, 1 ) ) * pow ( self::$configs ['base'], $len - $t );
		}
		$ret -= self::$configs ['offset'];
		return $ret;
	}
}